package com.zbl.zblproject.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.zbl.zblproject.core.entity.AdminUser;
import com.zbl.zblproject.core.entity.Result;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.service.ErpAllotService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/24
 */
@RestController
@Api(tags = {"调拨订单接口"})
@RequestMapping("/erp-allot")
public class ErpAllotController {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ErpAllotService allotService;


    private static final Logger logger = LoggerFactory.getLogger(ErpAllotController.class);


    @PostMapping("/rollback/{id}")
    @ApiOperation("回滚调拨单")
    public Result rollback(@ApiParam("客户ID") @RequestParam("userId") int userId,
                         @ApiParam("订单ID") @PathVariable int id){
        try {
            AdminUser user = getUserById(userId);
            boolean result = allotService.rollback(id);
            if(result) {
                return ResultUtil.success("成功!");
            }else{
                return ResultUtil.error("失败");
            }
        }catch(RuntimeException e){
            logger.warn(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }
    }


    @PostMapping("/create/{orderNo}/{status}")
    @ApiOperation("创建调拨单")
    public Result create(@ApiParam("订单号") @PathVariable String orderNo,
                                @ApiParam("客户ID") @RequestParam("userId") int userId,
                                @ApiParam("订单状态") @PathVariable int status,
                                @RequestParam("items") String items){
        try {
            AdminUser user = getUserById(userId);
          //  logger.info("json数据: {}", items);
            ErpAllotOrder order = allotService.createOrderByStatus(orderNo, status, user, parseJson(items));
            return ResultUtil.success("成功!");
        }catch(RuntimeException e){
            logger.warn(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }
    }

    @GetMapping("/desc/{orderNo}")
    @ApiOperation("获取订单下的所有")
    public Result descOrder(@ApiParam("订单号") @PathVariable String orderNo){

        try{
            List<ErpAllotOrderItem> list =  allotService.orderItemByOrderSn(orderNo);
            return ResultUtil.success("成功!", list);
        }catch(RuntimeException e){
            logger.info(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }
    }


    @PostMapping("/update/{orderNo}")
    @ApiOperation("更新调拨单订单状态")
    public Result update(@ApiParam("订单号") @PathVariable String orderNo){

        try{

            if(allotService.updateOrder(orderNo)){
                return ResultUtil.success("成功!");
            }else{
                return ResultUtil.error("失败");
            }
        }catch(RuntimeException e){
            logger.info(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除调拨单订单")
    public Result deleteOrder(@ApiParam("删除订单") @PathVariable int id){
        if(allotService.deleteOrderById(id)){
            return ResultUtil.success("成功!");
        }else{
            return ResultUtil.error("失败!");
        }
    }


    @GetMapping("/list/{current}/{size}")
    @ApiOperation("入库订单列表查询")
    public Result listByIn(@ApiParam("查询页数") @PathVariable int current,
                           @ApiParam("查询数量") @PathVariable int size,
                           @ApiParam("查询订单号") @RequestParam("search") String search,
                           @ApiParam("起始时间") @RequestParam("start") String start,
                           @ApiParam("结束时间") @RequestParam("end") String end,
                           @ApiParam("查询用户姓名") @RequestParam("user") String user,
                           @ApiParam("查询状态 -1 为查询全部") @RequestParam("status") int status){
        String searchStr = searchStr(search, start, end, user, status);
        return ResultUtil.success("成功",  allotService.page(searchStr, current, size));
    }


    private List<ErpAllotOrderItem> parseJson(String json){
     //   logger.info("json数据: {}", json);
        List<ErpAllotOrderItem> list = new ArrayList<>();

        JSONArray array = JSONArray.parseArray(json);
        JSONObject object;
        ErpAllotOrderItem orderItem;
        for(int i = 0; i < array.size(); i++){
            object = array.getJSONObject(i);
            orderItem = new ErpAllotOrderItem();
            orderItem.setGoodsId(object.getInteger("goodsId"));

            if(object.containsKey("goodsNum")){
                orderItem.setNumber(object.getInteger("goodsNum"));
            }

            if(object.containsKey("number")){
                orderItem.setNumber(object.getInteger("number"));
            }

            if(object.containsKey("toWhid")){
                orderItem.setToWh(object.getInteger("toWhid"));
                if(orderItem.getToWh() == 0){
                    throw new RuntimeException("商品:" + object.getString("goodsName") + "未选择入库仓库库位!");
                }
            }else{
                throw new RuntimeException("商品:" + object.getString("goodsName") + "未选择入库仓库库位!");
            }

            if(object.containsKey("goodsList")){
                orderItem.setFromWh(object.getInteger("goodsList"));
                if(orderItem.getFromWh() == 0){
                    throw new RuntimeException("商品:" + object.getString("goodsName") + "未选择出库仓库库位!");
                }
            }else{
                throw new RuntimeException("商品:" + object.getString("goodsName") + "未选择出库仓库库位!");
            }

            list.add(orderItem);
        }
        return list;
    }



    private AdminUser getUserById(int userId){
        AdminUser user = adminUserMapper.selectById(userId);
        Preconditions.checkNotNull(user, "用户不存在!");
        if(user.getStatus() != 0){
            throw new RuntimeException("用户被封禁!");
        }
        return user;
    }
    private String searchStr(String search, String start, String end, String user, int status){
        StringBuilder buffer = new StringBuilder();
        buffer.append(" DATE_FORMAT(create_time, '%Y-%m-%d') >= ");
        buffer.append("'").append(start).append("'");
        buffer.append(" AND ");
        buffer.append(" DATE_FORMAT(create_time, '%Y-%m-%d') <= ");
        buffer.append("'").append(end).append("'");

        if(!Strings.isNullOrEmpty(search.trim())) {
            buffer.append(" AND");
            buffer.append(" allot_sn LIKE '%");
            buffer.append(StringUtil.sql(search));
            buffer.append("%' ");
        }

        if(!Strings.isNullOrEmpty(user.trim())){
            buffer.append(" AND");
            buffer.append(" operator LIKE '%");
            buffer.append(StringUtil.sql(user));
            buffer.append("%' ");
        }

        if(status != -1){
            buffer.append(" AND");
            buffer.append(" status = ").append(status);
        }

        logger.info("条件语句: "+buffer.toString());
        return buffer.toString();
    }



}
